<!--
 * @Descripttion: 可编辑table
 * @version: V1.0
 * @Author: GW
 * @Date: 2021-11-16 14:01:24
 * @LastEditors: GW
 * @LastEditTime: 2021-11-16 17:10:28
-->
<template>
    <div class="table-box">
        <a-table v-if="isRouterAlive" id="process_edit_tb" class="atable-edit" :columns="columnsAdd" :customRow="customClick" :data-source="dataSource" :pagination="false" bordered :scroll="{x:1000,y:384}">
            <template v-for="item in editColumnArraya" :slot="item" slot-scope="text, record ,index">
                <div :key="item">
                    <editable-cell v-if="isRouterAlive" :record="record" :col="item" :text="text" @change="onCellChange(index, item, $event)" />
                </div>
            </template>
        </a-table>
        <div class="edit-mask-route" v-show="editMask">
            <!-- 遮罩（点击修改关闭遮罩） -->
        </div>
        <div class="contextmenu-box">
            <!-- 右键菜单 -->
            <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                <li @click="handleAdd()">新增行</li>
                <li @click="handleDelete()">删除行</li>
                <!--  <li @click="handleCopy()">复制行</li> -->
            </ul>
        </div>
    </div>
</template>

<script>
import editableCell from "./editTable/EditableCell"
export default {
    components: {
        editableCell,
    },
    props: {
        dataSource: {
            type: Array,
            default: [],
        },
    },
    data () {
        return {
            visible: false,
            editMask: false,
            isRouterAlive: true,
            top: 0,
            left: 0,

            editColumnArraya: ['voucherTypeName', 'voucherFieldName', 'remark'],
            dataSourceNumber: 12,//默认渲染多少行表格数据
            thisClickId: null,
            customClick: (record, index) => {
                return {
                    on: {
                        contextmenu: (e) => {//右键事件
                            e.preventDefault();
                            if (index <= this.dataSource.length) {
                                this.openMenu(e);
                                console.log('右键点击的', index);
                                this.thisClickId = index;
                                // this.thisClickRecord = record;
                            }
                        },
                    }
                }
            },
            columns: [{
                title: '条码属性编码',
                dataIndex: 'code',
            },
            {
                title: '条码属性名称',
                dataIndex: 'name',
            },
            {
                title: '类型',
                dataIndex: 'type',
                customRender: (text, record, index) => {
                    return text == 1 ? '文本' : text == 2 ? '数字' : text == 3 ? '日期' : text == 4 ? '单据编号' : '';
                }
            },
            {
                title: '备注',
                dataIndex: 'remarks',
            },],
            columnsAdd: [{
                title: '序号',
                dataIndex: 'number',
                width: 40,
                align: 'center',
                customRender: (text, record, index) => {
                    return index + 1;
                }
            }, {
                title: '业务对象',
                dataIndex: 'voucherTypeName',
                scopedSlots: { customRender: 'voucherTypeName' },
            },
            {
                title: '业务对象字段',
                dataIndex: 'voucherFieldName',
                scopedSlots: { customRender: 'voucherFieldName' },

            }, {
                title: '备注',
                dataIndex: 'remark',
                scopedSlots: { customRender: 'remark' },
            }],
            thisData: [], // 当前选中的数据
            selectedKeys: [],
            selectedRows: [],
        }
    },
    created () {
        this.tableInit();
    },
    watch: {
        visible (value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenu);
            } else {
                document.body.removeEventListener("click", this.closeMenu);
            }
        },
        dataSource (value) {
            this.dataSource = value;
            if (this.dataSource.length < this.dataSourceNumber) {
                for (let i = this.dataSource.length; i < this.dataSourceNumber; i++) {
                    let array = {
                        number: i + 1,
                    };
                    this.dataSource.push(array);
                }
            }
            this.$emit('updateObj', this.dataSource);
            this.reload();
        },
    },
    methods: {
        tableInit () {
            //初始化表格
            if (this.dataSource.length < this.dataSourceNumber) {
                for (let i = this.dataSource.length; i < this.dataSourceNumber; i++) {
                    let array = {
                        number: i + 1,
                    };
                    this.dataSource.push(array);
                }
            }
            this.reload();
            console.log(this.dataSource)
        },
        reload () {
            //强制刷新表格
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        openMenu (e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.top = y;
            this.left = x;
            this.visible = true;
        },
        closeMenu () {
            //隐藏右键菜单
            this.visible = false;
        },
        handleAdd () {
            //新增数据
            const { count, dataSource } = this;
            const newData = {};
            this.$nextTick(() => {
                this.dataSource.splice(this.dataSource.length, 0, newData);
            })
            console.log('新增行：', this.dataSource)
        },
        handleDelete () {
            //删除整行
            let _this = this;
            let numberId = this.thisClickId;
            console.log(numberId);
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk () {
                    let dataSource = [..._this.dataSource];
                    console.log(_this.dataSource.length);
                    if (dataSource.length - 1 > _this.dataSourceNumber) {
                        //大于规定行数(删除)
                        _this.dataSource = dataSource.filter((item, index) => index !== numberId);
                    } else {
                        //小于规定行数(清空)
                        for (let i = 0; i < dataSource.length; i++) {
                            if (i === numberId) {
                                for (const key in dataSource[i]) {
                                    if (key != 'number') {
                                        dataSource[i][key] = ""
                                    }
                                }
                            }
                        }
                        _this.dataSource = dataSource;
                    }


                    _this.reload();
                },
                onCancel () { },
            });
        },
        onCellChange (indexTable, dataIndex, value) {
            const dataSource = [...this.dataSource];
            const target = dataSource.find((item, index) => index === indexTable);
            console.log(target, dataIndex, value, indexTable);

            this.$set(target, dataIndex, value)
            if (dataIndex == 'voucherTypeCode' || dataIndex == 'voucherTypeName') {
                if (value) {
                    target['voucherTypeCode'] = value.voucherTypeCode;
                    target['voucherTypeName'] = value.voucherTypeName;
                } else {
                    target['voucherTypeCode'] = '';
                    target['voucherTypeName'] = '';
                }
            }

            if (dataIndex == 'voucherField' || dataIndex == 'voucherFieldName') {
                if (value) {
                    target['voucherField'] = value.code;
                    target['voucherFieldId'] = value.id;
                    target['voucherFieldName'] = value.name;
                } else {
                    target['voucherField'] = '';
                    target['voucherFieldId'] = '';
                    target['voucherFieldName'] = '';

                }
            }

            this.$nextTick(() => {
                this.dataSource = dataSource;
                console.log('明细数据：', this.dataSource)
                this.reload();
            })

        },
        onSelectChange (keys, rows) {
            this.selectedKeys = keys;
            this.selectedRows = rows;
        },
    }
}
</script>

<style lang="less">
    // @import '~@/style/setting/inventory.less';
    @import '~@/style/purchase/voucher.less';
    .table-wrapper-box {
        height: calc(100% - 45px);
        padding: 10px;
    }
    .order-warpper-box {
        padding: 10px;
        overflow-y: auto;
    }
    .barcode-box {
        .ant-form-item {
            margin-bottom: 0px;
        }
    }
</style>
